<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同Id" prop="contractId">
        <el-input
          v-model="queryParams.contractId"
          placeholder="请输入合同Id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="甲方单位" prop="partyAUnit">
        <el-input
          v-model="queryParams.partyAUnit"
          placeholder="请输入甲方单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="甲方联系人" prop="partyAContact">
        <el-input
          v-model="queryParams.partyAContact"
          placeholder="请输入甲方联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="甲方联系人联系方式" prop="partyAContactInfo">
        <el-input
          v-model="queryParams.partyAContactInfo"
          placeholder="请输入甲方联系人联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="乙方单位" prop="partyBUnit">
        <el-input
          v-model="queryParams.partyBUnit"
          placeholder="请输入乙方单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="乙方联系人" prop="partyBContact">
        <el-input
          v-model="queryParams.partyBContact"
          placeholder="请输入乙方联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="乙方联系人联系方式" prop="partyBContactInfo">
        <el-input
          v-model="queryParams.partyBContactInfo"
          placeholder="请输入乙方联系人联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行时间" prop="executionTime">
        <el-date-picker clearable
                        v-model="queryParams.executionTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择执行时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入合同总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
                        v-model="queryParams.createdAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
                        v-model="queryParams.updatedAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:contract:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:contract:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:contract:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="合同ID" align="center" prop="contractId"/>
      <el-table-column label="合同名称" align="center" prop="contractName"/>
      <el-table-column label="甲方单位" align="center" prop="partyAUnit"/>
      <el-table-column label="甲方联系人" align="center" prop="partyAContact"/>
      <el-table-column label="甲方联系人联系方式" align="center" prop="partyAContactInfo"/>
      <el-table-column label="乙方单位" align="center" prop="partyBUnit"/>
      <el-table-column label="乙方联系人" align="center" prop="partyBContact"/>
      <el-table-column label="乙方联系人联系方式" align="center" prop="partyBContactInfo"/>
      <el-table-column label="参与人员" align="center" prop="participants"/>
      <el-table-column
        label="合同内容"
        align="center"
        prop="content"
        show-overflow-tooltip
      />

      <el-table-column label="考核指标" align="center" prop="indicators"/>
      <el-table-column label="执行时间" align="center" prop="executionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.executionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同总金额" align="center" prop="totalAmount"/>
      <el-table-column label="文件路径" align="center" prop="filePath"/>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:contract:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:contract:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称"/>
        </el-form-item>
        <el-form-item label="关联项目id" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入关联项目id"/>
        </el-form-item>
        <el-form-item label="甲方单位" prop="partyAUnit">
          <el-input v-model="form.partyAUnit" placeholder="请输入甲方单位"/>
        </el-form-item>
        <el-form-item label="甲方联系人" prop="partyAContact">
          <el-input v-model="form.partyAContact" placeholder="请输入甲方联系人"/>
        </el-form-item>
        <el-form-item label="甲方联系人联系方式" prop="partyAContactInfo">
          <el-input v-model="form.partyAContactInfo" placeholder="请输入甲方联系人联系方式"/>
        </el-form-item>
        <el-form-item label="乙方单位" prop="partyBUnit">
          <el-input v-model="form.partyBUnit" placeholder="请输入乙方单位"/>
        </el-form-item>
        <el-form-item label="乙方联系人" prop="partyBContact">
          <el-input v-model="form.partyBContact" placeholder="请输入乙方联系人"/>
        </el-form-item>
        <el-form-item label="乙方联系人联系方式" prop="partyBContactInfo">
          <el-input v-model="form.partyBContactInfo" placeholder="请输入乙方联系人联系方式"/>
        </el-form-item>
        <el-form-item label="参与人员" prop="participants">
          <el-input v-model="form.participants" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="合同内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="考核指标" prop="indicators">
          <el-input v-model="form.indicators" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="执行时间" prop="executionTime">
          <el-date-picker clearable
                          v-model="form.executionTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择执行时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入合同总金额"/>
        </el-form-item>
        <el-form-item label="上传合同" prop="filePath">
          <file-upload v-model="form.filePath" :fileType="['pdf', 'doc', 'docx', 'xls', 'xlsx']"/>
        </el-form-item>
        <el-form-item label="自动填写" prop="file">
          <!-- 原生 input，用 ref 拿到文件 -->
          <input
            type="file"
            ref="fileInput"
            @change="onFileChange"
            accept=".doc,.docx,.pdf"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="readFile">自动填写（请等待1-2分钟）</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
  readContract
} from "@/api/tongyan/contract";
import axios from 'axios'

export default {
  name: "Contract",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractName: null,
        partyAUnit: null,
        partyAContact: null,
        partyAContactInfo: null,
        partyBUnit: null,
        partyBContact: null,
        partyBContactInfo: null,
        participants: null,
        content: null,
        indicators: null,
        executionTime: null,
        totalAmount: null,
        filePath: null,
        createdAt: null,
        updatedAt: null,
        contractId: null
      },
      dialogVisible: false,
      // 表单参数
      form: {
        projectId: '',
        contractName: '',
        partyAUnit: '',
        partyAContact: '',
        partyAContactInfo: '',
        partyBUnit: '',
        partyBContact: '',
        partyBContactInfo: '',
        participants: '',
        content: '',
        indicators: '',
        executionTime: '',
        totalAmount: '',
        file: null
      },
      // 表单校验
      rules: {
        contractName: [
          {required: true, message: "合同名称不能为空", trigger: "blur"}
        ],
        projectId: [
          {required: true, message: '关联项目id不能为空', trigger: 'blur'}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    onFileChange(event) {
      const files = event.target.files
      this.form.file = files && files.length ? files[0] : null
    },
    async readFile() {
      if (!this.form.file) {
        this.$message.warning('请先选择要上传的合同文件')
        return
      }

      try {
        const resp = await readContract(this.form.file)

        if (!resp) {
          this.$message.warning('未提取到合同信息')
          return
        }

        // 填入表单
        this.form.contractName = resp['合同名称'] || ''
        this.form.partyAUnit = resp['甲方单位'] || ''
        this.form.partyAContact = resp['甲方联系人'] || ''
        this.form.partyAContactInfo = resp['甲方联系人联系方式'] || ''
        this.form.partyBUnit = resp['乙方单位'] || ''
        this.form.partyBContact = resp['乙方联系人'] || ''
        this.form.partyBContactInfo = resp['乙方联系人联系方式'] || ''
        this.form.content = resp['合同内容'] || ''
        this.form.totalAmount = resp['合同总金额'] || ''
        this.$message.success('读取成功，已填入表单')
      } catch (err) {
        console.error(err)
        this.$message.error('调用接口失败：' + (err.response?.data || err.message))
      }
    },



    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractName: null,
        partyAUnit: null,
        partyAContact: null,
        partyAContactInfo: null,
        partyBUnit: null,
        partyBContact: null,
        partyBContactInfo: null,
        participants: null,
        content: null,
        indicators: null,
        executionTime: null,
        totalAmount: null,
        filePath: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const contractId = row.contractId || this.ids
      getContract(contractId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.contractId != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$modal.confirm('是否确认删除合同，编号为"' + contractIds + '"的数据项？').then(function () {
        return delContract(contractIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
